package com.org.gameloft.GLIDER.plugins.server;


import com.org.gameloft.GLIDER.common.JarResources;
import com.org.gameloft.GLIDER.plugins.base.GLIDERPlugin;

import java.util.Properties;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: Fili
 * Date: Jul 31, 2007
 * Time: 11:22:05 PM
 */
public class PluginInfo
{
    public static final String PLUGIN_DEFAULT_DESC = "plugin.properties";
    
    private Properties properties;
    
    private PluginLoader loader;
    private GLIDERPlugin plugin;
    private String path;


    public GLIDERPlugin getPlugin()
    {
        return plugin;
    }

    public boolean isLoaded()
    {
        return (plugin != null);
    }

    public String getProperty(String key)
    {
        return properties.getProperty(key);
    }

    public String getProperty(String key, String defaultValue)
    {
        return properties.getProperty(key, defaultValue);
    }

    private PluginInfo(Properties properties, String path)
    {
        this.properties = properties;
        this.path = path;
    }

    public static PluginInfo getInfo(String path)
    {
        JarResources jr = new JarResources(path);

        byte[] b = jr.getResource(PLUGIN_DEFAULT_DESC);
        if (b == null)
            return null;

        Properties prop = new Properties();
        try
        {
            prop.load(new ByteArrayInputStream(b));
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }

        if (prop.getProperty("plugin.class") == null)
            return null;
        
        return new PluginInfo(prop, path);
    }

    public boolean load()
    {
        if (isLoaded())
            return false;

        
        loader = new PluginLoader(path);
        Class cls;
        Object obj;

        String className = getProperty("plugin.class");

        if (className == null)
            return false;

        try
        {
            cls = loader.loadClass(className);
            obj = cls.newInstance();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }

        if (obj instanceof GLIDERPlugin)
        {
            plugin = (GLIDERPlugin) obj;
            plugin.init();
            return true;
        }

        return false;
    }

    public void unload()
    {
        plugin.uninit();
        loader = null;
        plugin = null;
    }

    public void reload()
    {
        unload();
        load();
    }
}
